<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="教师" prop="realname" style="width: 150px">
        <el-input
          v-model="queryParams.realname"
          placeholder="教师姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工号" prop="teacherCode" style="width: 180px">
        <el-input
          v-model="queryParams.teacherCode"
          placeholder="请输入工号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学院名称" prop="collegeName" style="width: 200px">
        <el-input
          v-model="queryParams.collegeName"
          placeholder="学院名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否有课" prop="isClass" style="width: 150px">
        <el-select
          v-model="queryParams.isClass"
          placeholder="请选择"
          clearable
          @change="handleQuery"
        >
          <el-option label="有课" :value="1" />
          <el-option label="无课" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="预约状态" prop="reservationStatus" style="width: 150px">
        <el-select
          v-model="queryParams.reservationStatus"
          placeholder="请选择"
          clearable
          @change="handleQuery"
        >
          <el-option label="预约成功" :value="1" />
          <el-option label="候补中" :value="2" />
          <el-option label="已取消" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:reservation:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Upload"
          :disabled="multiple"
          @click="handleBatchUpdate"
          v-hasPermi="['system:reservation:edit']"
          >批量修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:reservation:remove']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="reservationList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="教师姓名" align="center" prop="realname" />
      <el-table-column label="工号" align="center" prop="teacherCode" />
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="学院名称" align="center" prop="collegeName" />
      <el-table-column label="至目的地是否有课" align="center" prop="isClass">
        <template #default="scope">
          <span>{{ scope.row.isClass === 1 ? "有课" : "无课" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预约时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预约状态" align="center" prop="reservationStatus">
        <template #default="scope">
          <span v-for="dict in reservationStatusOptions" :key="dict.value">
            <span v-if="scope.row.reservationStatus === dict.value">{{
              dict.label
            }}</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:reservation:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:reservation:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改存储教师预约记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="reservationRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="教师姓名" prop="realname">
          <el-input v-model="form.realname" placeholder="请输入教师姓名" disabled />
        </el-form-item>
        <el-form-item label="工号" prop="teacherCode">
          <el-input v-model="form.teacherCode" placeholder="请输入工号" disabled />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" disabled />
        </el-form-item>
        <el-form-item label="学院名称" prop="collegeName">
          <el-input v-model="form.collegeName" placeholder="请输入学院名称" disabled />
        </el-form-item>
        <el-form-item label="是否有课" prop="isClass">
          <el-radio-group v-model="form.isClass" disabled>
            <el-radio :label="1">有课</el-radio>
            <el-radio :label="2">无课</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="预约时间" prop="createTime">
          <el-date-picker
            clearable
            v-model="form.createTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择预约时间"
            disabled
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预约状态" prop="reservationStatus">
          <el-select v-model="form.reservationStatus" placeholder="请选择预约状态">
            <el-option
              v-for="dict in reservationStatusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 批量修改预约记录对话框 -->
    <el-dialog
      :title="batchUpdateTitle"
      v-model="batchUpdateOpen"
      width="500px"
      append-to-body
    >
      <el-form
        ref="batchUpdateRef"
        :model="batchUpdateForm"
        :rules="batchUpdateRules"
        label-width="100px"
      >
        <el-form-item label="预约状态" prop="reservationStatus">
          <el-select
            v-model="batchUpdateForm.reservationStatus"
            placeholder="请选择预约状态"
          >
            <el-option
              v-for="dict in reservationStatusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <!-- 关联日期选择项 - 加载getDatesOptions方法获取的日期列表数据 -->
        <el-form-item label="关联日期" prop="dateId">
          <el-select v-model="batchUpdateForm.dateId" placeholder="请选择关联日期">
            <el-option
              v-for="item in dateOptions"
              :key="item.id"
              :label="`${item.dateInfo} - ${item.licensePlate} (${item.maxCapacity}座) - ${item.lineLabel}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitBatchUpdate">确 定</el-button>
          <el-button @click="cancelBatchUpdate">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Reservation">
import {
  listReservation,
  getReservation,
  delReservation,
  addReservation,
  updateReservation,
} from "@/api/busmanagement/reservation";
import { listDate, selectByDate } from "@/api/busmanagement/date";

import { useRoute } from "vue-router";
import { watch } from "vue";

const { proxy } = getCurrentInstance();
const route = useRoute(); // 初始化路由

// 监听路由query中dateId的变化并更新查询参数
watch(
  () => route.query.dateId,
  (newVal) => {
    queryParams.value.dateId = newVal || null;
    // 路由变化后自动刷新列表数据
    handleQuery();
  },
  { immediate: false }
);

const reservationList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
/** 批量修改对话框标题 - 固定显示为"批量修改预约记录" */
const batchUpdateTitle = ref("批量修改预约记录");
/** 批量修改对话框显示状态控制 - true为显示，false为隐藏 */
const batchUpdateOpen = ref(false);
/** 日期选项列表 - 存储从selectByDate接口获取的格式化日期数据，用于下拉选择器渲染 */
const dateOptions = ref([]);

// 往返线路选项
const lineOptions = ref([
  { value: 1, label: "上午-青州---潍坊" },
  { value: 2, label: "下午-青州---潍坊" },
  { value: 3, label: "上午-潍坊---青州" },
  { value: 4, label: "下午-潍坊---青州" },
]);

// 预约状态字典
const reservationStatusOptions = ref([
  { value: 1, label: "预约成功" },
  { value: 2, label: "候补中" },
  { value: 3, label: "已取消" },
]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    dateId: route.query.dateId || null,
    realname: null,
    teacherCode: null,
    phone: null,
    collegeName: null,
    isClass: null,
    reservationStatus: null,
    queueNum: null,
    cancelTime: null,
  },
  rules: {
    dateId: [{ required: true, message: "关联 t_bus_date.id不能为空", trigger: "blur" }],
    realname: [{ required: true, message: "教师姓名不能为空", trigger: "blur" }],
    teacherCode: [{ required: true, message: "工号不能为空", trigger: "blur" }],
    phone: [{ required: true, message: "手机号不能为空", trigger: "blur" }],
    reservationStatus: [
      { required: true, message: "预约状态不能为空", trigger: "change" },
    ],
    createTime: [{ required: true, message: "预约时间不能为空", trigger: "blur" }],
    updateTime: [{ required: true, message: "更新时间不能为空", trigger: "blur" }],
  },
  // 批量修改表单
  batchUpdateForm: {
    dateId: null,
    reservationStatus: null,
  },
  // 批量修改表单验证规则
  batchUpdateRules: {
    dateId: [{ required: true, message: "关联日期不能为空", trigger: "change" }],
    reservationStatus: [
      { required: true, message: "预约状态不能为空", trigger: "change" },
    ],
  },
});

const { queryParams, form, rules, batchUpdateForm, batchUpdateRules } = toRefs(data);

/** 获取日期选项列表
 * 功能：调用listDate接口获取日期数据并格式化为下拉组件所需结构
 * 处理逻辑：
 * 1. 调用listDate接口获取原始日期数据
 * 2. 将原始数据映射为{id: 日期ID, dateInfo: 日期显示文本}格式
 * 3. 异常捕获并提示获取失败信息
 */
async function getDatesOptions() {
  try {
    // 调用listDate接口获取日期数据
    console.log("reservationList.value.createTime:", reservationList.value[0].createTime);
    const response = await selectByDate(reservationList.value[0].createTime);
    // 格式化日期选项，添加车牌号和最大容量
    dateOptions.value = response.data.map((item) => {
      const lineLabel = item.tBusSchedule
        ? lineOptions.value.find((line) => line.value === item.tBusSchedule.line)?.label
        : "N/A";
      return {
        id: item.id,
        dateInfo: item.departureData, // 假设departureData是日期信息
        licensePlate: item.tBus ? item.tBus.licensePlate : "N/A", // 获取车牌号
        maxCapacity: item.tBus ? item.tBus.maxCapacity : "N/A", // 获取最大容量
        lineLabel: lineLabel, // 获取路线信息
      };
    });
  } catch (error) {
    proxy.$modal.msgError("获取日期选项失败");
    console.error("获取日期选项失败", error);
  }
}

/** 取消批量修改操作
 * 功能：关闭批量修改对话框并重置表单数据
 * 处理逻辑：
 * 1. 隐藏批量修改对话框
 * 2. 重置批量修改表单的dateId和reservationStatus字段为null
 * 3. 调用全局重置表单方法清空验证状态
 */
function cancelBatchUpdate() {
  batchUpdateOpen.value = false;
  // 重置批量修改表单
  batchUpdateForm.value = {
    dateId: null,
    reservationStatus: null,
  };
  proxy.resetForm("batchUpdateRef");
}

/** 查询存储教师预约记录列表 */
function getList() {
  loading.value = true;
  listReservation(queryParams.value).then((response) => {
    reservationList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    dateId: route.query.dateId || null,
    realname: null,
    teacherCode: null,
    phone: null,
    collegeName: null,
    isClass: null,
    reservationStatus: null,
    queueNum: null,
    createTime: null,
    cancelTime: null,
    updateTime: null,
  };
  // 重置批量修改表单
  batchUpdateForm.value = {
    dateId: null,
    reservationStatus: null,
  };
  proxy.resetForm("reservationRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 批量修改按钮点击事件处理
 * 功能：验证选中数据并打开批量修改对话框
 * 处理逻辑：
 * 1. 检查是否选中至少一条数据，未选中则提示警告
 * 2. 显示批量修改对话框
 * 3. 调用getDatesOptions方法加载日期选项列表
 */
function handleBatchUpdate() {
  if (ids.value.length === 0) {
    proxy.$modal.msgWarning("请选择要修改的数据项！");
    return;
  }
  batchUpdateOpen.value = true;
  getDatesOptions(); // 获取日期选项
}

/** 提交批量修改操作
 * 功能：验证表单并循环调用updateReservation接口修改选中数据
 * 处理逻辑：
 * 1. 验证批量修改表单数据有效性
 * 2. 显示加载状态提示
 * 3. 循环遍历选中ID，构造单个修改请求参数并调用updateReservation接口（顺序执行避免服务器压力）
 * 4. 操作成功：提示成功信息、关闭对话框、刷新列表
 * 5. 操作失败：提示失败信息并打印错误日志
 * 6. 最终关闭加载状态提示
 */
function submitBatchUpdate() {
  proxy.$refs["batchUpdateRef"].validate(async (valid) => {
    if (valid) {
      proxy.$modal.loading("正在批量修改预约记录，请稍候...");
      try {
        for (const id of ids.value) {
          const updateForm = {
            id: id,
            dateId: batchUpdateForm.value.dateId,
            reservationStatus: batchUpdateForm.value.reservationStatus,
          };
          await updateReservation(updateForm);
        }
        proxy.$modal.msgSuccess("批量修改成功");
        batchUpdateOpen.value = false;
        getList();
      } catch (error) {
        proxy.$modal.msgError("批量修改失败");
        console.error("批量修改失败", error);
      } finally {
        proxy.$modal.closeLoading();
      }
    }
  });
}

getList();
function resetQuery() {
  proxy.resetForm("queryRef");
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加存储教师预约记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getReservation(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改存储教师预约记录";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["reservationRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateReservation(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addReservation(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除存储教师预约记录编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delReservation(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "reservation/reservation/export",
    {
      ...queryParams.value,
    },
    `reservation_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>
